import java.util.ArrayList;
import java.util.HashMap;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MySaxHandler extends DefaultHandler {
	private boolean isBody = false;
	private boolean isMessage = false;
	private String startTagName;
	private ArrayList<HashMap> messageList = new ArrayList<HashMap>();
	private HashMap<String, String> messageMap = new HashMap<String, String>();
	private String tmpValue;

	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (qName.equalsIgnoreCase("BODY")) {
			isBody = true;
			System.out.println("[[...Body parsing start...]]");
		} else if (isBody && qName.equalsIgnoreCase("MESSAGE")) {
			isMessage = true;
			messageMap = new HashMap<String, String>();
			for (int i = 0; i < attributes.getLength(); i++) {
				messageMap.put(attributes.getQName(i), attributes.getValue(i));
				System.out.println("--------- col " + attributes.getQName(i));
				System.out.println("--------- val " + attributes.getValue(i));
			}
		} else if (isBody && isMessage) {
			startTagName = qName;
		}
	}

	public void endElement(String namespaceURI, String localName, String qName)
			throws SAXException {
		if (qName.equalsIgnoreCase("BODY")) {
			System.out.println("[[...Body parsing end...]]");
			isBody = false;
		} else if (isBody && qName.equalsIgnoreCase("message")) {
			isMessage = false;
			messageList.add(messageMap);
			System.out.println("--------------- message add!! -------------");
			// messageMap.clear();
		} else if (isBody && isMessage) {
			messageMap.put(startTagName, tmpValue);
			System.out.println("--------- col " + startTagName.trim());
			System.out.println("--------- val " + tmpValue.trim());
			tmpValue = "";
		}
	}

	public void characters(char ch[], int start, int length)
			throws SAXException {
		tmpValue = new String(ch, start, length);
	}

	public ArrayList<HashMap> getMessageList() {
		return messageList;
	}
}